/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.utils.h2

import cool.taomu.utils.inter.IStorage
import java.io.Serializable
import java.util.Arrays
import java.util.Map
import org.apache.commons.lang3.SerializationUtils

class H2CacheUtils implements IStorage {
	var h2 = new H2Utils;

	new() {
		var table = "CREATE TABLE IF NOT EXISTS h2cache(id varchar(255) ,ckey varchar(255),cvalue text,primary key(id,ckey));"
		h2.modify(table);
	}

	override put(String identifier, String key, Serializable value) {
		var sql = "insert into h2cache(id,ckey,cvalue) values(?,?,?)";
		var bytes = SerializationUtils.serialize(value);
		var result = new String(bytes,"UTF-8");
		h2.modify(sql,#[identifier,key,result].toArray);
	}

	override get(String identifier, String key) {
		var sql = "select cvalue from h2cache where id=? and ckey=?";
		var result = h2.select(sql,Map,Arrays.asList(identifier,key).toArray).get(0);
		var byteStr = result.get("cvalue") as String;
		var bytes = byteStr.bytes;
		return SerializationUtils.deserialize(bytes);
	}

	override remove(String identifier, String key) {
		var sql = "delete from h2cache where id=? and ckey=?";
		h2.modify(sql,Arrays.asList(identifier,key).toArray);
	}

	override clear(String identifier) {
		throw new UnsupportedOperationException("TODO: auto-generated method stub")
	}

}
